import { trim, startsWith } from 'lodash'
import { request as _request } from './request'
import { parseRule } from './parser'
import { load } from 'cheerio'
import { parseSearchUrl, v2 as _v2 } from './common'

function parseBook (source: any, doc: string) {
  if (source.ruleSearch) {
    return v3.parseBook(source, doc)
  } else {
    return v2.parseBook(source, doc)
  }
}

async function downloadBook (source: any, bookUrl: string) {
  if (source.ruleSearch) {
    return v3.downloadBook(source, bookUrl)
  } else {
    return v2.downloadBook(source, bookUrl)
  }
}

const v3 = {
  parseBook (source: any, doc: string) {
    const $ = load(doc)

    const bookMap = source.ruleBookInfo

    const items: any = {}

    Object.keys(bookMap).forEach(prop => {
      items[prop] = trim(parseRule(bookMap[prop], $) as string)
    })

    return items
  },

  async  downloadBook (source: any, bookUrl: string) {
    if (!startsWith(bookUrl, 'http')) {
      bookUrl = source.bookSourceUrl + bookUrl
    }
    const { options } = parseSearchUrl(source)
    return _request(bookUrl, options)
  }
}

const v2 = {
  parseBook (source: any, doc: string) {
    const $ = load(doc)

    const bookMap: Record<string, string> = {
      infoInit: source.ruleBookInfoInit,
      name: source.ruleBookName,
      author: source.ruleBookAuthor,
      kind: source.ruleBookKind,
      lastChapter: source.ruleBookLastChapter,
      intro: source.ruleIntroduce,
      coverUrl: source.ruleCoverUrl,
      chapterUrl: source.ruleChapterUrl,
      chapterUrlNext: source.ruleChapterUrlNext
    }

    const item: any = {}
    Object.keys(bookMap).forEach(prop => {
      item[prop] = trim(parseRule(bookMap[prop], $) as string)
    })

    return item
  },

  async  downloadBook (source: any, bookUrl: string) {
    if (!startsWith(bookUrl, 'http')) {
      bookUrl = source.bookSourceUrl + bookUrl
    }
    const { options } = _v2.parseSearchUrl(source)
    return _request(bookUrl, options)
  }
}

export {
  parseBook,
  downloadBook
}
